package com.chcit.mobile.mvp.hight.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.xuexiang.xui.widget.dialog.materialdialog.GravityEnum;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.button.SwitchButton;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.NfcUtils;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.entity.HightCostBindBean;
import com.chcit.mobile.mvp.hight.adapter.HightCostBindAdapter;
import com.chcit.mobile.mvp.hight.contract.HightCostBindContract;
import com.chcit.mobile.mvp.hight.di.component.DaggerHightCostBindComponent;
import com.chcit.mobile.mvp.hight.presenter.HightCostBindFragmentPresenter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class HightCostBindFragment extends ScanFragment<HightCostBindFragmentPresenter> implements HightCostBindContract.View {

    public static HightCostBindFragment newInstance() {
        HightCostBindFragment fragment = new HightCostBindFragment();
        return fragment;
    }
    @BindView(R.id.bt_hcb_bind)
    Button btBind;
    @BindView(R.id.et_hcb_productName)
    SuperEditText etHcbProductName;
    @BindView(R.id.bt_hcb_query)
    Button btHcbQuery;
    @BindView(R.id.ll_hcb_first)
    LinearLayout llHcbFirst;
    @BindView(R.id.tv_hight_cost_bind_sernoName)
    TextView tvHightCostBindSernoName;
    @BindView(R.id.tv_hight_cost_bind_RFIDName)
    TextView tvHightCostBindRFIDName;
    @BindView(R.id.lv_hcb_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.bt_hcb_ok)
    Button btHcbOk;
    @BindView(R.id.cb_hcb_bind)
    AppCompatCheckBox cbBind;
    @BindView(R.id.cb_hcb_auto)
    AppCompatCheckBox chAuto;
    SuperInputEditText etRFID;
    @BindView(R.id.button_start_search)
    SwitchButton switchRFID;
    @BindView(R.id.ddm_hight_bind_date)
    DropDownMenu mDropDownMenu;
    private SuperInputEditText etBindPackagNo;
    private MaterialDialog buder;
    private HightCostBindAdapter mAdapter;
    private List<HightCostBindBean> packageBeanList = new ArrayList<>();
    boolean NFC_flag = true;
    private   TextView tvError;
    private SuperTextView tvDateFrom;
    private SuperTextView tvDateTo;
    private BpartnerBean bpartnerBean;
    private ArrayList<BpartnerBean> bpartners;
    private String headers[] = {"选择日期"};
    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerHightCostBindComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_hight_cost_bind, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        new NfcUtils(_mActivity);
        initRecyclerView();
        initDialog();
//        etHcbProductName.addTextChangedListener(textWatcher);
        switchRFID.setOnCheckedChangeListener((view, isChecked) -> {
            Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
            _mActivity.startActivity(setNfc);
        });
        initDropDownMenu();
    }

    @Override
    public void setData(@Nullable Object data) {
        if (data instanceof Message) {
            Message message = (Message) data;
            switch (message.what) {
                case 0:
                    Intent intent = (Intent)message.obj;
                    if(NFC_flag){
                        String str = NfcUtils.readNfcID(intent);
                        if(buder.isShowing()){
                            etRFID.setText(str);
                        }else{
                            buder.show();
                            etRFID.setText(str);
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        // etHcbProductName.setText(barcodeData);
        if(etHcbProductName.isFocused()&&!buder.isShowing()&&!cbBind.isChecked()){
             etHcbProductName.setText(barcodeData);
             btHcbQuery.performClick();
         }else  if(buder.isShowing()){
            if(etBindPackagNo.isFocused()){
                etBindPackagNo.setText(barcodeData);
                if(etRFID.getText().length()>0&&chAuto.isChecked()){
                    if(etRFID.getText().toString().equals(etBindPackagNo.getText().toString())){
                        String message =  "<font color='#FFC125'><big>警告:</big></font><font color='#EEEE00'>包装码和RFID码一样</font>";
                        showDialogError(message);
                    }else {
                        bindData();
                    }
                }else{
                    etRFID.requestFocus();
                }

            }else{
                etRFID.setText(barcodeData);
                if(etBindPackagNo.getText().length()>0&&chAuto.isChecked()){
                    if(etBindPackagNo.getText().toString().equals(etRFID.getText().toString())){
                      String message =  "<font color='#FFC125'><big>警告: </big></font><font color='#A8A8A8'><big>包装码和RFID码一样!</big></font>";
                      showWarning(message);
                    }else{
                        bindData();
                    }

                }

            }

        }else {
            etBindPackagNo.setText(barcodeData);
            btBind.performClick();
        }

    }

    private void initRecyclerView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL));

        mAdapter = new HightCostBindAdapter(packageBeanList);
//        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);
//        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
//        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        mAdapter.setOnItemClickListener(
                (adapter, view, position) -> {
                    if(position>-1&&mAdapter.getData().size()>0){
                        mAdapter.setCheckedPosition(position);
                        new MaterialDialog.Builder(mContext)
                                .content(mAdapter.getData().get(position).toString())
                                .show();
                    }

                }
        );
        mAdapter.setOnImageClickListener((adapter, view, position)->{
            unBindData(String.valueOf(mAdapter.getData().get(position).getRFID()),v->{
                mAdapter.remove(position);
            });
        });
//        OnItemDragListener listener = new OnItemDragListener() {
//            @Override
//            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
//                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
////                holder.setTextColor(R.id.tv, Color.WHITE);
//            }
//
//            @Override
//            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
//
//            }
//
//            @Override
//            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
//                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
////                holder.setTextColor(R.id.tv, Color.BLACK);
//            }
//        };
//        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
//            int position ;
//            @Override
//            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
//                position = pos;
//            }
//
//            @Override
//            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {
//
//            }
//
//            //删除item
//            @Override
//            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
//                if(pos!= -1){
//                    position = pos;
//                }
//                unBindData(packageBeanList.get(position).getRFID(),null);
//            }
//
//            @Override
//            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
//                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));
//
//            }
//        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
     //   mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        //        mAdapter.enableSwipeItem();
        //        mAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
//        mAdapter.enableDragItem(mItemTouchHelper);
//        mAdapter.setOnItemDragListener(listener);
        mRecyclerView.setAdapter(mAdapter);
    }
    private void initDialog() {

        buder = new MaterialDialog.Builder(mContext)
                .title("RFID绑定")
                .titleGravity(GravityEnum.CENTER)
                .customView(R.layout.dialog_scan_rfid, true)
                .positiveText("确认")
                .negativeText("取消")
                .cancelable(false)
                .autoDismiss(false)
                .onPositive((dialog, which) -> {
                    bindData();

                })
                .onNegative((dialog, which) -> {
                    etBindPackagNo.setText("");
                    etRFID.setText("");
                    tvError.setVisibility(View.INVISIBLE);
                    dialog.dismiss();
                })
                .build();
        etRFID = buder.getCustomView().findViewById(R.id.et_RFID);
        tvError = buder.getCustomView().findViewById(R.id.tv_dialog_error);
        etBindPackagNo = buder.getCustomView().findViewById(R.id.tv_dialog_bind_packageNo);
//        etHcbProductName.setFocusable(true);
//        etHcbProductName.setFocusableInTouchMode(true);
        etBindPackagNo.requestFocus();

    }

    public void bindData(){
        if(etRFID.getText().length()>0&&etBindPackagNo.getText().length()>0){
            mPresenter.bindPackage(etRFID.getText().toString(),etBindPackagNo.getText().toString(),()->{
                buder.dismiss();
                showMessage("绑定成功！");
                etRFID.setText("");
                etBindPackagNo.setText("");
                getData();

            });
        }

//        PHPClient.build()
//                .method(URLContains.HIGHT_COST_BIND)
//                //.params("bpartnerId", "")
//                .params("bind", bind)
//                .invoke(new PHPClient.PHPClientListener() {
//                    @Override
//                    public void onFinish(String result) {
//                        QuickLoader.stopLoading();
//                        mAdapter.addData(hightCostBindBean);
//
//
//                    }
//
//                    @Override
//                    public void onError(Throwable error) {
//                        ExceptionUtils.printf(HightCostBindActivity.this,error);
//                        QuickLoader.stopLoading();
//                    }
//                });
    }
    public void unBindData(String RFID, View.OnClickListener v){

        mPresenter.unBindPackage(RFID,()->{
            if(v!=null){
                v.onClick(null);
            }
            showMessage("解绑成功！");
        });
//        PHPClient.build()
//                .method(URLContains.HIGHT_COST_UN_BIND)
//                //.params("bpartnerId", "")
//                .params("RFID", bind)
//                .invoke(new PHPClient.PHPClientListener() {
//                    @Override
//                    public void onFinish(String result) {
//                        QuickLoader.stopLoading();
//                        Toast.makeText(HightCostBindActivity.this,"删除成功",Toast.LENGTH_LONG).show();
//                        if(v!= null){
//                            v.onClick(null);
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable error) {
//                        ExceptionUtils.printf(HightCostBindActivity.this,error);
//                        QuickLoader.stopLoading();
//                    }
//                });
   }
    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();
        //日期选择
        final View dateView = getLayoutInflater().inflate(R.layout.pop_date, null);
        tvDateTo = dateView.findViewById(R.id.pop_date_drive);
        tvDateFrom = dateView.findViewById(R.id.pop_date_from);
        TextView ok = dateView.findViewById(R.id.ok);
        tvDateFrom.setCenterString(TimeDialogUtil.getBeforeDay(0));
        tvDateFrom.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateFrom.setCenterString(s), 0));
        tvDateTo.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateTo.setCenterString(s), 0));
        tvDateFrom.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3,
                        s->{
                            tvDateFrom.setCenterString(s);
                            ok.performClick();
                        },
                        0,calendar);
            }
        });
        tvDateTo.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->{
                    tvDateTo.setCenterString(s);
                    ok.performClick();
                }, 0,calendar);


            }
        });

        ok.setOnClickListener(v -> {
            StringBuffer text = new StringBuffer();
            if(!tvDateFrom.getCenterString().isEmpty()){
                text.append("开始日期：");
                text.append(tvDateFrom.getCenterString()) ;
            }
            if(!tvDateTo.getCenterString().isEmpty()){
                text .append("\n结束日期："+ tvDateTo.getCenterString());
            }

            mDropDownMenu.setTabText(text==null? headers[0] : text.toString());
            mDropDownMenu.closeMenu();
        });
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Collections.singletonList("开始日期：" + TimeDialogUtil.getBeforeDay(0));
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);
        tvDateTo.setRightImageViewClickListener(l -> {
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l -> {
            tvDateFrom.setCenterString("");
        });

    }
    @OnClick({R.id.bt_hcb_query, R.id.bt_hcb_bind})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_hcb_query:
                if(etHcbProductName.getText().length()>0 && packageBeanList.size()>0){
                    HightCostBindBean packageBean = new HightCostBindBean(etHcbProductName.getText().toString());
                    int position = packageBeanList.indexOf(packageBean);
                    if (position >= 0) {
                        new MaterialDialog.Builder(mContext)
                                .title("提示")
                                .content("该条码已被扫过，是否解绑？")
                                .negativeText("解绑")
                                .positiveText("取消")
                                .onNegative((dialog, which) -> {
                                    unBindData(String.valueOf(packageBeanList.get(position).getRFID()),v->{
                                        mAdapter.remove(position);
                                    });
                                })
                                .build()
                                .show();
                        return;
                    }else{
                        getData();
                    }
                }else {
                    getData();
                }

                break;
            case R.id.bt_hcb_bind:
                buder.show();
                etBindPackagNo.requestFocus();
                if(etBindPackagNo.getText().length()>0){
                    etBindPackagNo.setText(etBindPackagNo.getText());
                    etRFID.requestFocus();
                }
                break;
        }
    }
    private void getData(){
        mAdapter.getData().clear();
        JSONObject queryParam = new JSONObject();
        if(etHcbProductName.getText().length()>0){
            queryParam.put("value",etHcbProductName.getText().toString());
        }
        if (!tvDateFrom.getCenterTextView().getText().toString().isEmpty()) {
            queryParam.put("dateFrom", tvDateFrom.getCenterTextView().getText().toString());
        }
        if (!tvDateTo.getCenterTextView().getText().toString().isEmpty()) {
            queryParam.put("dateTo", tvDateTo.getCenterTextView().getText().toString());
        }
        queryParam.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        queryParam.put("limit",9999);
        mPresenter.queryBindPakcage(queryParam,list->{
            if(list.size()> 0){
                mAdapter.addData(list);
            }else{
                showMessage("无绑定信息！");
            }
        });
    }
    private TextWatcher textWatcher = new TextWatcher() {
        int mEditTextHaveInputCount = 0 ;
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                if (mEditTextHaveInputCount == 0) {
                    btHcbQuery.setEnabled(false);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            //EditText最初内容为空 改变EditText内容时 个数加一
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                // 判断个数是否到达要求
                int EDITTEXT_AMOUNT = 1;

                if (mEditTextHaveInputCount >= EDITTEXT_AMOUNT) {
                    btHcbQuery.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public void onPause() {
        super.onPause();
        //关闭前台调度系统
        NfcUtils.mNfcAdapter.disableForegroundDispatch(_mActivity);
    }

    @Override
    public void onResume() {
        super.onResume();
        //开启前台调度系统
        NfcUtils.mNfcAdapter.enableForegroundDispatch(_mActivity, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);
        if(isVisibleOnScreen()&&NfcUtils.mNfcAdapter != null){
            NFC_flag = NfcUtils.mNfcAdapter.isEnabled();
            if(switchRFID.isChecked()!= NFC_flag){
                switchRFID.setChecked(NFC_flag);
            }
        }
    }

    @Override
    public void showDialogError(String error) {

       tvError.setVisibility(View.VISIBLE);
       tvError.setText(error);

    }
    public void showWarning(String error) {

        tvError.setVisibility(View.VISIBLE);
        tvError.setText(Html.fromHtml(error));

    }
}
